using Godot;
using System;

public partial class Barb : AnimatedSprite2D
{
	public Enemy enemy;

	public Player player;

	public Vector2 directionOfMovement;

	public Timer timer;

	public Area2D area2D;
	
	public VisibleOnScreenNotifier2D visibleOnScreenNotifier2D;

	public bool IsTimeout = false;

	[Export]
	public int Speed = 3;

	public override void _Ready()
	{
		enemy = GetNode<Enemy>("/root/Main/Enemy");

		player = GetNode<Player>("/root/Main/Player");

		timer = GetNode<Timer>("Timer");
		timer.Timeout+=OnTimeout;

		visibleOnScreenNotifier2D = GetNode<VisibleOnScreenNotifier2D>("VisibleOnScreenNotifier2D");
		visibleOnScreenNotifier2D.ScreenExited+=OnExitScreen;

		area2D = GetNode<Area2D>("Area2D");
		area2D.BodyEntered+=OnCollision;
		area2D.SetCollisionMaskValue(2,false);

		AnimationFinished+=OnBreak;
	}

    public override void _Process(double delta)
    {
        if(IsTimeout)
		{
			Position+=Speed*directionOfMovement;
		}
    }

	private void OnExitScreen()
    {
		enemy.RemoveChild(this);
		QueueFree();
    }


    private void OnTimeout()
    {
        IsTimeout = true;
		directionOfMovement = (player.Position-Position).Normalized();
    }

    public void OnCollision(Node2D body)
    {
        if(body.Name == "Floor"||body.Name == "Player")
		{
			GD.Print("Barb collided "+body.Name);
			
			GetNode<AudioStreamPlayer2D>("BreakMusic").Play();

			player.OnHurt();

			Animation = "break";
			Speed = 0;
		}
    }

	public void OnBreak()
	{
		if(Animation == "break")
		{
			enemy.RemoveChild(this);
			QueueFree();
		}
	}
}
